<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TradingView 实时图表</title>
    <script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script>

    <style>
        
    </style>
</head>
<body style="background: #000;">
    <div id="tv_chart_container"></div>
    <script type="text/javascript">

        async function reactNativeCallHandler(funcName, params, timeout = 30000) {
            // 生成唯一请求ID
            const requestId = Date.now().toString();

            return new Promise((resolve, reject) => {
                // 检查是否处于 React Native 环境
                if (!window.ReactNativeWebView) {
                    return reject({ code: 1, msg: '未处于ReactNative环境中' });
                }

                // 添加一次性监听器
                const responseHandler = (event) => {
                    try {
                        const data = event.data
                        if (data.requestId == requestId) {
                            // 移除监听器
                            window.removeEventListener('message', responseHandler);
                            if (data.code != 0) {
                                return reject(data);
                            }
                            resolve(data.payload);
                        }
                    } catch (error) {
                        reject({ code: 1, msg: `解析消息出错: ${error.message}` });
                    }
                };

                window.addEventListener('message', responseHandler);

                // 发送请求
                window.ReactNativeWebView.postMessage(
                    JSON.stringify({
                        funcName,
                        params,
                        requestId
                    })
                );

                // 设置超时
                const timeoutId = setTimeout(() => {
                    // 移除监听器
                    window.removeEventListener('message', responseHandler);
                    reject({ code: 1, msg: 'Native接口响应超时' });
                }, timeout);

                // 在 Promise 解决或拒绝时清除超时定时器
                const cleanup = () => {
                    clearTimeout(timeoutId);
                    window.removeEventListener('message', responseHandler);
                };

                // 监听 Promise 的解决和拒绝事件
                const originalResolve = resolve;
                const originalReject = reject;
                resolve = (value) => {
                    cleanup();
                    originalResolve(value);
                };
                reject = (reason) => {
                    cleanup();
                    originalReject(reason);
                };
            });
        }

        let currentSymbol = '';

        // 初始化函数
        async function init() {
            try {
                // 调用 RN 方法获取 tradingSymbol
                const result = await reactNativeCallHandler('getTradingSymbolFunction', {});
                currentSymbol = result.result;
                console.log('获取到的 tradingSymbol:', currentSymbol);

                // 初始化 TradingView 图表
                new TradingView.widget(
                    {
                        "width": "100%",
                        "height": "349px",
                        "symbol": currentSymbol, 
                        "interval": "1",
                        "timezone": "Etc/UTC",
                        "theme": "dark",
                        "style": "1",
                        "locale": "zh_CN",
                        "toolbar_bg": "#f1f3f6",
                        "enable_publishing": false,
                        "allow_symbol_change": true,
                        "container_id": "tv_chart_container",
                        "realtimeRefreshDelay": 1 
                    }
                );

                // 开始获取市场信息
                fetchMarketInfo();
            } catch (error) {
                console.error('初始化失败:', error);
            }
        }

        let retryCount = 0;
        const MAX_RETRIES = 3;
        const BASE_INTERVAL = 1000; 

        async function fetchMarketInfo() {
            if (!currentSymbol) {
                console.error('tradingSymbol 未获取到，无法请求数据');
                return;
            }
            try {
                const response = await fetch(`https://api.binance.com/api/v3/ticker/24hr?symbol=${currentSymbol}`);
                if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
                const data = await response.json();
                // 将 24 小时数据发送给 RN
                await reactNativeCallHandler('get24hVolumeFunction', {
                    highPrice: parseFloat(data.highPrice).toFixed(2),
                    lowPrice: parseFloat(data.lowPrice).toFixed(2),
                    volume: parseFloat(data.volume).toFixed(2),
                    quoteVolume: parseFloat(data.quoteVolume).toFixed(2)
                });

                retryCount = 0; // 请求成功，重置重试次数
                // 使用 setTimeout 递归调用
                setTimeout(fetchMarketInfo, BASE_INTERVAL);
            } catch (error) {
                console.error('获取市场信息失败:', error);
                retryCount++;
                if (retryCount <= MAX_RETRIES) {
                    // 指数退避策略，每次重试间隔加倍
                    const retryInterval = BASE_INTERVAL * Math.pow(2, retryCount); 
                    setTimeout(fetchMarketInfo, retryInterval);
                } else {
                    console.error('达到最大重试次数，停止尝试');
                }
            }
        }

        // 页面加载完成后执行初始化
        window.onload = init;
    </script>
</body>
</html>
